import React, { useState, useEffect } from 'react';
import { http, API_PATH } from '../utils/http';
import html2canvas from 'html2canvas';
import MarkdownRenderer from '../components/MarkdownRenderer';
import { Layout, Card, Button, Modal, Tag, Select, Spin, message, Space, Typography, Input, Avatar, Collapse } from 'antd';
import {
    ArrowLeftOutlined,
    ReloadOutlined,
    CopyOutlined,
    DownloadOutlined,
    EditOutlined,
    CaretRightOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';

const { Header, Content } = Layout;
const { Title, Text } = Typography;
const { TextArea } = Input;
const { Panel } = Collapse;

// 文章主题状态类型
type ArticleStatus = 'pending' | 'completed' | 'processing' | 'failed';

// 文章详情接口
interface ArticleDetail {
    id: string;
    user: string;
    display_name: string; // 添加用户显示名称
    topic_id: string;
    topic: string;
    article_status: ArticleStatus;
    article_content: string;
    article_title: string;
    article_title_status: ArticleStatus;
    cover_status: ArticleStatus;
    cover_html: string;
    created_at: number;
    is_used: boolean; // 是否已使用
}

// 状态文本映射
const statusTextMap: Record<ArticleStatus, string> = {
    pending: '待执行',
    completed: '完成执行',
    processing: '执行中',
    failed: '执行失败'
};

// 状态颜色映射
const statusColorMap: Record<ArticleStatus, string> = {
    pending: 'blue',
    completed: 'success',
    processing: 'processing',
    failed: 'error'
};

const TopicDetailPage: React.FC = () => {
    const [topicId] = useState<string | null>(() => {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get('id');
    });
    const [loading, setLoading] = useState(false);
    const [articles, setArticles] = useState<ArticleDetail[]>([]);
    const [coverEditor, setCoverEditor] = useState<{
        visible: boolean;
        articleId: string;
        html: string;
    }>({
        visible: false,
        articleId: '',
        html: ''
    });
    const [confirmDialog, setConfirmDialog] = useState<{
        visible: boolean;
        detailId: string;
    }>({
        visible: false,
        detailId: ''
    });

    // 获取文章详情
    const fetchArticleDetail = async (id: string, includeUsed: boolean = false) => {
        if (!id) return;

        setLoading(true);
        try {
            const params = {
                topic_id: id,
                is_used: includeUsed
            };

            const response = await http.get<ArticleDetail[]>(API_PATH.ARTICLE.ARTICLE_DETAIL, params);

            response.onSuccess(() => {
                if (response.data && Array.isArray(response.data) && response.data.length > 0) {
                    setArticles(response.data);
                } else {
                    message.info('未找到相关文章详情');
                }
            }).onError((code, msg) => {
                console.error(`获取详情失败: 错误码 ${code}, 消息: ${msg}`);
                message.error(`获取文章详情失败: ${msg}`);
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            message.error('网络请求异常');
        } finally {
            setLoading(false);
        }
    };

    // 格式化时间
    const formatDate = (timestamp: number) => {
        return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
    };

    // 复制文章内容
    const handleCopy = (content: string) => {
        navigator.clipboard.writeText(content)
            .then(() => message.success('复制成功'))
            .catch(() => message.error('复制失败'));
    };

    // 重新生成标题
    const handleRegenerateTitle = async (detailId: string) => {
        try {
            setLoading(true);
            const response = await http.post<string>(API_PATH.ARTICLE.REGENERATE_TITLE, { detail_id: detailId });

            response.onSuccess(() => {
                message.success('标题生成任务已加入队列');
                setTimeout(() => {
                    if (topicId) {
                        fetchArticleDetail(topicId);
                    }
                }, 3000);
            }).onError((code, msg) => {
                console.error(`标题重新生成失败: 错误码 ${code}, 消息: ${msg}`);
                message.error(`标题重新生成失败: ${msg}`);
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            message.error('网络请求异常');
        } finally {
            setLoading(false);
        }
    };

    // 重新生成封面
    const handleRegenerateCover = async (detailId: string) => {
        try {
            setLoading(true);
            const response = await http.post<{
                detail_id: string;
                job_id: string;
            }>(API_PATH.ARTICLE.REGENERATE_COVER, { detail_id: detailId });

            response.onSuccess(() => {
                message.success('封面生成任务已加入队列');
                setTimeout(() => {
                    if (topicId) {
                        fetchArticleDetail(topicId);
                    }
                }, 3000);
            }).onError((code, msg) => {
                console.error(`重新生成失败: 错误码 ${code}, 消息: ${msg}`);
                message.error(`重新生成失败: ${msg}`);
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            message.error('网络请求异常');
        } finally {
            setLoading(false);
        }
    };

    // 重新生成文章内容
    const handleRegenerateArticle = async (detailId: string) => {
        try {
            setLoading(true);
            const response = await http.post<{
                detail_id: string;
                job_id: string;
            }>(API_PATH.ARTICLE.RETRY_FAILED, { detail_id: detailId });

            response.onSuccess(() => {
                message.success('文章内容重试任务已加入队列');
                setTimeout(() => {
                    if (topicId) {
                        fetchArticleDetail(topicId);
                    }
                }, 3000);
            }).onError((code, msg) => {
                console.error(`重新生成文章失败: 错误码 ${code}, 消息: ${msg}`);
                message.error(`重新生成文章失败: ${msg}`);
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            message.error('网络请求异常');
        } finally {
            setLoading(false);
        }
    };

    // 下载封面图片
    const handleDownloadCover = async (articleId: string) => {
        try {
            message.loading('正在生成图片...', 0);
            const coverElement = document.getElementById(`cover-${articleId}`);
            if (!coverElement) {
                message.error('获取封面元素失败');
                return;
            }

            const currentArticle = articles.find(article => article.id === articleId);
            if (!currentArticle) {
                message.error('获取文章信息失败');
                return;
            }

            let titleFromHTML = '';
            try {
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = currentArticle.cover_html;
                const titleTag = tempDiv.querySelector('title');
                if (titleTag && titleTag.textContent) {
                    titleFromHTML = titleTag.textContent.trim();
                } else {
                    const titleElement = tempDiv.querySelector('h1, h2, h3, h4, h5, h6');
                    if (titleElement && titleElement.textContent) {
                        titleFromHTML = titleElement.textContent.trim();
                    }
                }
            } catch (error) {
                console.error('从HTML提取标题失败:', error);
            }

            let downloadFilename = titleFromHTML || currentArticle.article_title || '封面';
            downloadFilename = downloadFilename
                .replace(/[/\\:*?"<>|]/g, '')
                .substring(0, 50);

            const date = new Date();
            const dateStr = `${date.getFullYear()}${(date.getMonth() + 1).toString().padStart(2, '0')}${date.getDate().toString().padStart(2, '0')}`;
            const randomCode = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
            downloadFilename = `${downloadFilename}_${dateStr}_${randomCode}`;

            await new Promise(resolve => setTimeout(resolve, 500));

            const canvas = await html2canvas(coverElement, {
                allowTaint: true,
                useCORS: true,
                scale: 2,
                logging: true,
                backgroundColor: null,
                onclone: (_document, clonedElement) => {
                    const contentElement = clonedElement.querySelector('.cover');
                    if (contentElement) {
                        const htmlElement = clonedElement as HTMLElement;
                        htmlElement.style.padding = '0';
                        htmlElement.style.margin = '0';
                        htmlElement.style.border = 'none';
                        htmlElement.style.borderRadius = '0';
                        htmlElement.style.boxShadow = 'none';
                        htmlElement.style.background = 'none';

                        while (clonedElement.firstChild) {
                            clonedElement.removeChild(clonedElement.firstChild);
                        }
                        clonedElement.appendChild(contentElement);

                        const contentHtmlElement = contentElement as HTMLElement;
                        contentHtmlElement.style.width = '100%';
                        contentHtmlElement.style.height = '100%';
                        contentHtmlElement.style.margin = '0';
                        contentHtmlElement.style.padding = '0';
                        contentHtmlElement.style.border = 'none';
                    }
                    return clonedElement;
                }
            });

            const imageUrl = canvas.toDataURL('image/png');
            const link = document.createElement('a');
            link.href = imageUrl;
            link.download = downloadFilename + '.png';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            message.destroy();
            message.success('下载成功');
        } catch (error) {
            message.destroy();
            message.error('下载封面失败: ' + (error as Error).message);
        }
    };

    // 更新文章使用状态
    const handleUpdateUsageStatus = async (detailId: string, isUsed: boolean) => {
        try {
            setLoading(true);
            const response = await http.post<{
                detail_id: string;
                is_used: boolean;
            }>(API_PATH.ARTICLE.UPDATE_USAGE_STATUS, {
                detail_id: detailId,
                is_used: isUsed
            });

            response.onSuccess(() => {
                message.success('文章使用状态更新成功');
                if (topicId) {
                    fetchArticleDetail(topicId);
                }
            }).onError((code, msg) => {
                console.error(`更新使用状态失败: 错误码 ${code}, 消息: ${msg}`);
                message.error(`更新使用状态失败: ${msg}`);
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            message.error('网络请求异常');
        } finally {
            setLoading(false);
        }
    };

    // 处理重新生成确认
    const handleConfirmRegenerate = () => {
        if (confirmDialog.detailId) {
            handleRegenerateArticle(confirmDialog.detailId);
        }
        setConfirmDialog({ visible: false, detailId: '' });
    };

    // 打开封面编辑器
    const openCoverEditor = (articleId: string, html: string) => {
        console.log('打开封面编辑器', articleId, html.substring(0, 30) + '...');
        setCoverEditor({
            visible: true,
            articleId,
            html
        });
    };

    // 关闭封面编辑器
    const closeCoverEditor = () => {
        setCoverEditor({
            visible: false,
            articleId: '',
            html: ''
        });
    };

    // 更新封面HTML
    const updateCoverHTML = (html: string) => {
        setCoverEditor(prev => ({
            ...prev,
            html
        }));
    };

    // 保存封面修改
    const saveCoverChanges = async () => {
        try {
            setLoading(true);
            const response = await http.post<{
                detail_id: string;
                cover_html: string;
            }>(API_PATH.ARTICLE.UPDATE_COVER, {
                detail_id: coverEditor.articleId,
                cover_html: coverEditor.html
            });

            response.onSuccess(() => {
                const updatedArticles = articles.map(article => {
                    if (article.id === coverEditor.articleId) {
                        return {
                            ...article,
                            cover_html: coverEditor.html
                        };
                    }
                    return article;
                });

                setArticles(updatedArticles);
                message.success('封面修改已保存');
                closeCoverEditor();
            }).onError((code, msg) => {
                console.error(`保存封面修改失败: 错误码 ${code}, 消息: ${msg}`);
                message.error(`保存封面修改失败: ${msg}`);
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            message.error('网络请求异常');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (topicId) {
            fetchArticleDetail(topicId, true);
        } else {
            message.error('未找到主题ID');
        }
    }, [topicId]);

    const handleBack = () => {
        window.history.back();
    };

    const renderStatusBadge = (status: ArticleStatus) => (
        <Tag color={statusColorMap[status]}>{statusTextMap[status]}</Tag>
    );

    return (
        <Layout className="min-h-screen bg-[#f8fafc]">
            <Header className="bg-white border-b border-gray-100 flex items-center px-8 h-16">
                <div className="flex w-full items-center justify-between">
                    <Button
                        type="text"
                        icon={<ArrowLeftOutlined />}
                        onClick={handleBack}
                        className="text-gray-500 hover:text-gray-900 transition-colors"
                    >
                        返回
                    </Button>
                    <Title level={4} className="absolute left-1/2 transform -translate-x-1/2 mb-0 text-gray-800 font-medium">创作详情</Title>
                    <div className="w-[60px]"></div> {/* 用于平衡布局的占位元素 */}
                </div>
            </Header>

            <Content className="p-8 max-w-6xl mx-auto">
                <Spin spinning={loading} tip="加载中...">
                    {articles.length > 0 ? (
                        <div className="space-y-6">
                            {/* 主题信息卡片 - 改为可折叠 */}
                            <Collapse
                                defaultActiveKey={[]}
                                className="bg-white rounded-xl border-0 shadow-sm hover:shadow-md transition-all duration-300"
                                expandIcon={({ isActive }) => (
                                    <CaretRightOutlined rotate={isActive ? 90 : 0} />
                                )}
                            >
                                <Panel header="主题信息" key="1" className="text-gray-800 font-medium">
                                    <div className="prose prose-sm max-w-none overflow-auto" style={{ maxHeight: '500px' }}>
                                        <MarkdownRenderer
                                            content={articles[0]?.topic || topicId || '未知主题'}
                                        />
                                    </div>
                                </Panel>
                            </Collapse>

                            {/* 文章列表 */}
                            {articles.map((article) => (
                                <Card
                                    key={article.id}
                                    className="bg-white rounded-xl border-0 shadow-sm hover:shadow-md transition-all duration-300"
                                    title={
                                        <div className="flex items-center justify-between">
                                            <Space>
                                                <Avatar className="bg-blue-100 text-blue-600">
                                                    {article.display_name?.[0] || article.user?.[0] || 'U'}
                                                </Avatar>
                                                <div>
                                                    <div className="text-sm font-medium text-gray-900">
                                                        {article.display_name || article.user}
                                                    </div>
                                                    <div className="text-xs text-gray-500">
                                                        {formatDate(article.created_at)}
                                                    </div>
                                                </div>
                                            </Space>
                                            <Select
                                                value={article.is_used ? 'true' : 'false'}
                                                onChange={(value) => handleUpdateUsageStatus(article.id, value === 'true')}
                                                style={{ width: 100 }}
                                                className="ml-4"
                                            >
                                                <Select.Option value="false">未使用</Select.Option>
                                                <Select.Option value="true">已使用</Select.Option>
                                            </Select>
                                        </div>
                                    }
                                    headStyle={{
                                        borderBottom: '1px solid #f1f5f9',
                                        padding: '20px 24px'
                                    }}
                                    bodyStyle={{ padding: '24px' }}
                                >
                                    {/* 文章内容部分 */}
                                    <div className="space-y-6">
                                        <div className="bg-gray-50 rounded-lg p-6">
                                            <div className="flex items-center justify-between mb-4">
                                                <Space>
                                                    <Text className="text-gray-900 font-medium">文章内容</Text>
                                                    {renderStatusBadge(article.article_status)}
                                                </Space>
                                                <Space>
                                                    <Button
                                                        type="primary"
                                                        icon={<ReloadOutlined />}
                                                        onClick={() => setConfirmDialog({ visible: true, detailId: article.id })}
                                                        className="bg-blue-500 hover:bg-blue-600 border-0"
                                                    >
                                                        重新生成
                                                    </Button>
                                                    {article.article_status === 'completed' && (
                                                        <Button
                                                            icon={<CopyOutlined />}
                                                            onClick={() => handleCopy(article.article_content)}
                                                            className="text-gray-600 hover:text-gray-900 border-0"
                                                        >
                                                            复制内容
                                                        </Button>
                                                    )}
                                                </Space>
                                            </div>
                                            {article.article_status === 'completed' ? (
                                                <div className="prose prose-sm max-w-none">
                                                    <MarkdownRenderer content={article.article_content} />
                                                </div>
                                            ) : (
                                                <div className="text-center text-gray-400 py-8">
                                                    {article.article_status === 'pending' ? '文章尚未生成' :
                                                        article.article_status === 'processing' ? '文章正在生成中...' :
                                                            '文章生成失败'}
                                                </div>
                                            )}
                                        </div>

                                        <div className="bg-gray-50 rounded-lg p-6">
                                            <div className="flex items-center justify-between mb-4">
                                                <Space>
                                                    <Text className="text-gray-900 font-medium">文章封面</Text>
                                                    {renderStatusBadge(article.cover_status)}
                                                </Space>
                                                <Space>
                                                    <Button
                                                        type="primary"
                                                        icon={<ReloadOutlined />}
                                                        onClick={() => handleRegenerateCover(article.id)}
                                                        className="bg-blue-500 hover:bg-blue-600 border-0"
                                                    >
                                                        重新生成
                                                    </Button>
                                                    {article.cover_status === 'completed' && (
                                                        <>
                                                            <Button
                                                                icon={<DownloadOutlined />}
                                                                onClick={() => handleDownloadCover(article.id)}
                                                                className="text-gray-600 hover:text-gray-900 border-0"
                                                            >
                                                                下载封面
                                                            </Button>
                                                            <Button
                                                                icon={<EditOutlined />}
                                                                onClick={() => openCoverEditor(article.id, article.cover_html)}
                                                                className="text-gray-600 hover:text-gray-900 border-0 hover:bg-blue-50"
                                                            >
                                                                修改内容
                                                            </Button>
                                                        </>
                                                    )}
                                                </Space>
                                            </div>
                                            {article.cover_status === 'completed' ? (
                                                <div id={`cover-${article.id}`} className="flex justify-center">
                                                    <div className="cover" dangerouslySetInnerHTML={{ __html: article.cover_html }} />
                                                </div>
                                            ) : (
                                                <div className="text-center text-gray-400 py-8">
                                                    {article.cover_status === 'pending' ? '封面尚未生成' :
                                                        article.cover_status === 'processing' ? '封面正在生成中...' :
                                                            '封面生成失败'}
                                                </div>
                                            )}
                                        </div>

                                        <div className="bg-gray-50 rounded-lg p-6">
                                            <div className="flex items-center justify-between mb-4">
                                                <Space>
                                                    <Text className="text-gray-900 font-medium">文章标题</Text>
                                                    {renderStatusBadge(article.article_title_status)}
                                                </Space>
                                                <Space>
                                                    <Button
                                                        type="primary"
                                                        icon={<ReloadOutlined />}
                                                        onClick={() => handleRegenerateTitle(article.id)}
                                                        className="bg-blue-500 hover:bg-blue-600 border-0"
                                                    >
                                                        重新生成
                                                    </Button>
                                                    {article.article_title_status === 'completed' && (
                                                        <Button
                                                            icon={<CopyOutlined />}
                                                            onClick={() => handleCopy(article.article_title)}
                                                            className="text-gray-600 hover:text-gray-900 border-0"
                                                        >
                                                            复制标题
                                                        </Button>
                                                    )}
                                                </Space>
                                            </div>
                                            {article.article_title_status === 'completed' ? (
                                                <div className="prose prose-sm max-w-none">
                                                    <MarkdownRenderer content={article.article_title} />
                                                </div>
                                            ) : (
                                                <div className="text-center text-gray-400 py-8">
                                                    {article.article_title_status === 'pending' ? '标题尚未生成' :
                                                        article.article_title_status === 'processing' ? '标题正在生成中...' :
                                                            '标题生成失败'}
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </Card>
                            ))}
                        </div>
                    ) : (
                        <Card className="text-center bg-white rounded-xl border-0 shadow-sm">
                            <Text type="secondary" className="text-lg">未找到文章详情</Text>
                        </Card>
                    )}
                </Spin>
            </Content>

            {/* 确认对话框 */}
            <Modal
                title="确认重新生成"
                open={confirmDialog.visible}
                onOk={handleConfirmRegenerate}
                onCancel={() => setConfirmDialog({ visible: false, detailId: '' })}
                okText="确认重新生成"
                cancelText="取消"
                okButtonProps={{ className: 'bg-blue-500 hover:bg-blue-600 border-0' }}
                className="rounded-lg"
            >
                <p className="text-gray-600">重新生成文章内容将同时重新生成标题和封面。是否确认重新生成？</p>
            </Modal>

            {/* 封面编辑器 - 使用自适应宽度和全屏优化 */}
            <Modal
                title="修改封面内容"
                open={coverEditor.visible}
                onOk={saveCoverChanges}
                onCancel={closeCoverEditor}
                width="100%"
                okText="保存修改"
                cancelText="取消"
                okButtonProps={{ className: 'bg-blue-500 hover:bg-blue-600 border-0' }}
                className="cover-editor-modal"
                zIndex={1001}
                maskClosable={false}
                destroyOnClose={false}
                forceRender={true}
                style={{ top: 20 }}
                bodyStyle={{
                    maxHeight: 'calc(100vh - 180px)',
                    overflow: 'auto',
                    padding: '24px'
                }}
                centered
            >
                <div className="flex flex-col lg:flex-row gap-6 h-full">
                    <div className="lg:w-1/2 w-full border rounded-lg p-4 bg-gray-50 overflow-auto"
                        style={{ minHeight: '70vh', maxHeight: 'calc(100vh - 250px)' }}>
                        <div className="cover-preview flex justify-center items-center h-full"
                            dangerouslySetInnerHTML={{ __html: coverEditor.html }} />
                    </div>
                    <div className="lg:w-1/2 w-full">
                        <TextArea
                            value={coverEditor.html}
                            onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => updateCoverHTML(e.target.value)}
                            className="font-mono text-sm w-full"
                            placeholder="请输入HTML内容..."
                            style={{ height: '70vh', maxHeight: 'calc(100vh - 250px)', resize: 'none' }}
                            onKeyDown={(e) => {
                                if (e.key === 'Tab') {
                                    e.preventDefault();
                                    const target = e.target as HTMLTextAreaElement;
                                    const value = target.value;
                                    const selectionStart = target.selectionStart;
                                    const selectionEnd = target.selectionEnd;
                                    const newValue = value.substring(0, selectionStart) + '  ' + value.substring(selectionEnd);
                                    updateCoverHTML(newValue);
                                    setTimeout(() => {
                                        target.selectionStart = target.selectionEnd = selectionStart + 2;
                                    }, 0);
                                }
                            }}
                        />
                    </div>
                </div>
            </Modal>
        </Layout>
    );
};

export default TopicDetailPage; 
